/*
 * HomeModel.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.data.model;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yidiandao.business.R;
import com.yidiandao.business.constant.Common;
import com.yidiandao.business.constant.Urls;
import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.constant.ServerType;
import com.yidiandao.business.data.imagemodule.DecorateImage;
import com.yidiandao.business.data.imagemodule.FlashSale;
import com.yidiandao.business.data.imagemodule.Free;
import com.yidiandao.business.data.imagemodule.ImageAD;
import com.yidiandao.business.data.imagemodule.MenuInfo;
import com.yidiandao.business.data.imagemodule.Notice;
import com.yidiandao.business.data.imagemodule.OneOneTwoImage;
import com.yidiandao.business.data.imagemodule.OneThreeImage;
import com.yidiandao.business.data.imagemodule.OneTwoImage;
import com.yidiandao.business.data.imagemodule.OneTwoOneImage;
import com.yidiandao.business.data.imagemodule.OneTwoThreeImage;
import com.yidiandao.business.data.imagemodule.SecondKill;
import com.yidiandao.business.data.imagemodule.ThreeImage;
import com.yidiandao.business.data.imagemodule.ThreeOneImage;
import com.yidiandao.business.data.imagemodule.TwoImage;
import com.yidiandao.business.data.recyclertype.DoubleGoods;
import com.yidiandao.business.data.request.PagerRequest;
import com.yidiandao.business.data.response.QueryFrameResponse;
import com.yidiandao.business.data.response.QueryGoodsListResponse;
import com.yidiandao.business.data.response.QueryHomeHeaderResponse;
import com.yidiandao.business.data.response.QuerySecondKillResponse;
import com.yidiandao.business.data.net.BaseRequest;
import com.yidiandao.business.data.net.NetBiz;
import com.yidiandao.business.data.net.NetListener;
import com.yidiandao.business.data.net.exception.BizErrorInfo;
import com.yidiandao.business.data.net.exception.NetErrorInfo;
import com.yidiandao.business.ui.widget.listview.DisplayListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeDecorateImageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeFlashSaleListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeFreeListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeGoodsListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeHotTitleListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeMenuListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeNoticeListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeOneBigImageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeOneOneTwoImageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeOneSmallImageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeOneThreeImageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeOneTwoImageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeOneTwoOneListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeOneTwoThreeImageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeSecondKillListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeServiceListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeThreeImageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeThreeOneImageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.HomeTwoImageListItem;
import com.yidiandao.business.utils.GsonProvider;
import com.yidiandao.business.utils.LogUtils;
import com.yidiandao.business.utils.PreferenceUtils;
import com.yidiandao.business.utils.UIUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页-Model
 */
public class HomeModel implements IHomeModel {

    private NetBiz mNetBiz = new NetBiz();

    private Gson mGson = GsonProvider.getGson();

    /**
     * 首页最新商品，品牌街单个品牌商品.由于两个使用不同的HomeModel对象，因此可以复用
     */
    private List<DoubleGoods> mGoodsGridList = new ArrayList<>();

    private List<Goods> mGoodsList = new ArrayList<>();

    private List<String> bannerUrls = new ArrayList<>();

    private List<DisplayListItem> mHomeDisplayItems = new ArrayList<>();

    private int goodsListPager;

    private long mServerNowTime;

    private FlashTimerTask flashTimerTask;

    private SecondKillTimer secondKillTimerTask;

    private int secondKillIndex;

    @Override
    public void loadHomeData(String tag, final OnLoadHomeHeaderListener listener) {

        final BaseRequest request = new BaseRequest();
        request.setTag(tag);
        request.setUrl(Urls.HOME);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));

        mNetBiz.sendGetRequest(
                request,
                QueryHomeHeaderResponse.class,
                new NetListener<QueryHomeHeaderResponse>() {
                    @Override
                    public void onSuccess(QueryHomeHeaderResponse response) {
                        // 先清除数据
                        bannerUrls.clear();
                        mHomeDisplayItems.clear();

                        QueryHomeHeaderResponse.Data data = response.getData();

                        // banner
                        List<QueryHomeHeaderResponse.Banner> banners = data.getBanners();
                        // 所有的所有类型
                        List<QueryHomeHeaderResponse.ImageModule> homeModules =
                                data.getImageModules();
                        // 将banner数据返回
                        if (banners != null) {
                            for (QueryHomeHeaderResponse.Banner banner : banners) {
                                bannerUrls.add(banner.getImage());
                            }
                        }

                        if (listener != null) {
                            listener.onBanner(banners, bannerUrls);
                        }

                        // 服务器的当前时间
                        mServerNowTime = data.getNowTime();

                        // 首页模块 以及 秒杀、免费赠送、限时抢购模块
                        if (homeModules != null && homeModules.size() != 0) {
                            for (QueryHomeHeaderResponse.ImageModule imageModule : homeModules) {
                                String type = imageModule.getType();
                                String info = imageModule.getInfo();

                                // 动态根据Type解析Info
                                DisplayListItem imageAdItem = parseImageModule(type, info);
                                if (imageAdItem != null) {
                                    mHomeDisplayItems.add(imageAdItem);
                                }
                            }
                        }

                        QueryHomeHeaderResponse.HomeGoods homeGoods = data.getHomeGoods();
                        if (homeGoods != null) {

                            // 流通商品
                            List<Goods> commodityGoodsList = homeGoods.getCommodityGoodsList();
                            if (commodityGoodsList != null && commodityGoodsList.size() != 0) {
                                mHomeDisplayItems.add(
                                        new HomeHotTitleListItem(R.mipmap.ic_home_commodity_goods));
                                mHomeDisplayItems.addAll(parseHomeGoodsListData(commodityGoodsList,
                                        -1));
                            }

                            // 热销商品列表
                            List<Goods> hotGoodsList = homeGoods.getHotGoodsList();
                            if (hotGoodsList != null && hotGoodsList.size() != 0) {
                                mHomeDisplayItems.add(
                                        new HomeHotTitleListItem(R.mipmap.ic_home_hot_goods));
                                mHomeDisplayItems.addAll(parseHomeGoodsListData(hotGoodsList,
                                        R.mipmap.ic_home_hot_goods_flag));
                            }

                            // 爆款商品列表
                            List<Goods> bestGoodsList = homeGoods.getBestGoodsList();
                            if (bestGoodsList != null && bestGoodsList.size() != 0) {
                                mHomeDisplayItems.add(
                                        new HomeHotTitleListItem(R.mipmap.ic_home_best_goods));
                                mHomeDisplayItems.addAll(parseHomeGoodsListData(bestGoodsList,
                                        R.mipmap.ic_home_best_goods_flag));
                            }

                            // 利润商品列表
                            List<Goods> profitGoodsList = homeGoods.getProfitGoodsList();
                            if (profitGoodsList != null && profitGoodsList.size() != 0) {
                                mHomeDisplayItems.add(
                                        new HomeHotTitleListItem(R.mipmap.ic_home_profit_goods));
                                mHomeDisplayItems.addAll(parseHomeGoodsListData(profitGoodsList,
                                        R.mipmap.ic_home_profit_goods_flag));
                                profitGoodsList.get(profitGoodsList.size() - 1).setLast(false);
                            }
                        }
                        if (listener != null) {
                            listener.onSuccess(mHomeDisplayItems);
                        }
                    }

                    @Override
                    public boolean onError(NetErrorInfo netErrorInfo) {
                        if (listener != null) {
                            listener.onFailed();
                        }
                        return true;
                    }

                    @Override
                    public boolean onFailed(BizErrorInfo bizErrorInfo) {
                        if (listener != null) {
                            listener.onFailed();
                        }
                        return true;
                    }

                    @Override
                    public void onFinal() {
                    }
                });
    }

    private List<DisplayListItem> parseHomeGoodsListData(List<Goods> goodsList,
                                                         int goodsFlagResId) {
        List<DisplayListItem> displayListItems = new ArrayList<>();
        goodsList.get(goodsList.size() - 1).setLast(true);
        if (goodsList != null && goodsList.size() != 0) {
            for (int i = 0; i < goodsList.size(); i += 2) {
                List<Goods> goodsLine = null;
                try {
                    goodsLine = goodsList.subList(i, i + 2);
                    goodsLine.get(0).setGoodsFlagResId(goodsFlagResId);
                    goodsLine.get(1).setGoodsFlagResId(goodsFlagResId);
                } catch (IndexOutOfBoundsException e) {
                    // 可能出现最后一个为null的情况
                    goodsLine = new ArrayList<>();
                    Goods lastGoods = goodsList.get(i);
                    lastGoods.setGoodsFlagResId(goodsFlagResId);
                    goodsLine.add(lastGoods);
                } finally {
                    displayListItems.add(new HomeGoodsListItem(goodsLine));
                }
            }
        }

        return displayListItems;
    }

    /**
     * 根据type动态解析首页模块
     *
     * @param type 模块的类型
     * @param info 模块的数据
     */
    private DisplayListItem parseImageModule(String type, String info) {
        // 根据 info 动态解析 type ---> 并返回一中类型
        DisplayListItem displayListItem = null;

        switch (type) {
            // 菜单
            case ServerType.Home.AD.MENU:
                displayListItem = new HomeMenuListItem(mGson.fromJson(info, MenuInfo.class));
                break;
            // 公告
            case ServerType.Home.AD.NOTICE:
                Type typeHelper = new TypeToken<List<Notice>>() {
                }.getType();
                List<Notice> notices = mGson.fromJson(info, typeHelper);
                displayListItem = new HomeNoticeListItem(notices);
                break;
            // 客服热线
            case ServerType.Home.AD.SERVICE_TEL:
                displayListItem = new HomeServiceListItem(null);
                break;
            // 装饰图片
            case ServerType.Home.AD.DECORATE_IMAGE:
                displayListItem =
                        new HomeDecorateImageListItem(mGson.fromJson(info, DecorateImage.class));
                break;
            // 图片模块
            case ServerType.Home.AD.ONE_BIG:
                displayListItem = new HomeOneBigImageListItem(mGson.fromJson(info, ImageAD.class));
                break;

            case ServerType.Home.AD.ONE_TWO_ONE:
                displayListItem =
                        new HomeOneTwoOneListItem(mGson.fromJson(info, OneTwoOneImage.class));
                break;

            case ServerType.Home.AD.ONE_ONE_TWO:
                displayListItem =
                        new HomeOneOneTwoImageListItem(mGson.fromJson(info, OneOneTwoImage.class));
                break;

            case ServerType.Home.AD.ONE_SMALL:
                displayListItem =
                        new HomeOneSmallImageListItem(mGson.fromJson(info, ImageAD.class));
                break;

            case ServerType.Home.AD.ONE_THREE:
                displayListItem =
                        new HomeOneThreeImageListItem(mGson.fromJson(info, OneThreeImage.class));
                break;

            case ServerType.Home.AD.ONE_TWO:
                displayListItem =
                        new HomeOneTwoImageListItem(mGson.fromJson(info, OneTwoImage.class));
                break;

            case ServerType.Home.AD.ONE_TWO_THREE:
                displayListItem =
                        new HomeOneTwoThreeImageListItem(
                                mGson.fromJson(info, OneTwoThreeImage.class));
                break;

            case ServerType.Home.AD.THREE:
                displayListItem =
                        new HomeThreeImageListItem(mGson.fromJson(info, ThreeImage.class));
                break;

            case ServerType.Home.AD.THREE_ONE:
                displayListItem =
                        new HomeThreeOneImageListItem(mGson.fromJson(info, ThreeOneImage.class));
                break;

            case ServerType.Home.AD.TWO:
                displayListItem = new HomeTwoImageListItem(mGson.fromJson(info, TwoImage.class));
                break;
            // 免费赠送
            case ServerType.Home.AD.FREE:
                displayListItem = new HomeFreeListItem(mGson.fromJson(info, Free.class));
                break;
            // 限时抢购
            case ServerType.Home.AD.LIMIT_TIME:
                // 给对象做一个计时器
                FlashSale flashSale = mGson.fromJson(info, FlashSale.class);
                // 开始倒计时
                doFlashSaleTimer(flashSale);
                displayListItem = new HomeFlashSaleListItem(flashSale);
                break;
            // 秒杀
            case ServerType.Home.AD.SECOND_KILL:
                // 保存SecondKillListItem的index
                secondKillIndex = mHomeDisplayItems.size();
                SecondKill secondKill = mGson.fromJson(info, SecondKill.class);
                // 设置服务器的当前时间
                secondKill.setServerNowTime(mServerNowTime);
                // 开始倒计时
                doSecondKillTimer(secondKill);
                displayListItem = new HomeSecondKillListItem(secondKill);
                break;
        }

        return displayListItem;
    }

    /**
     * 每隔一秒，动态改变 秒杀活动 对象的值
     */
    private void doSecondKillTimer(SecondKill secondKill) {
        if (secondKill == null || secondKill.getTimeInfo() == null) {
            // 活动结束后不会返回TimerInfo，直接结束定时器
            if (secondKillTimerTask != null) {
                secondKillTimerTask.stopTimer();
            }
            return;
        }

        if (secondKillTimerTask != null) {
            secondKillTimerTask.stopTimer();
            secondKillTimerTask = null;
        }

        secondKillTimerTask = new SecondKillTimer(secondKill);
        secondKillTimerTask.startTimer();
    }

    /**
     * 对象定时器，每隔一秒钟，动态改变 限时购 对象的值
     */
    private void doFlashSaleTimer(FlashSale flashSale) {

        List<Goods> flashGoodsList = flashSale.getGoodsList();

        Goods flashGoods1 = null;
        Goods flashGoods2 = null;
        Goods flashGoods3 = null;
        try {
            flashGoods1 = flashGoodsList.get(0);
            flashGoods2 = flashGoodsList.get(1);
            flashGoods3 = flashGoodsList.get(2);
        } catch (IndexOutOfBoundsException e) {
        } finally {
            // 启动对象计时器
            if (flashTimerTask != null) {
                flashTimerTask.stopTimer();
                flashTimerTask = null;
            }

            // 数据模拟
            //            mServerNowTime = 30;
            //
            //            if (flashGoods1 != null) {
            //                flashGoods1.setStartTime(50);
            //                flashGoods1.setEndTime(90);
            //            }
            //
            //            if (flashGoods2 != null) {
            //                flashGoods2.setStartTime(20);
            //                flashGoods2.setEndTime(50);
            //            }
            //
            //            if (flashGoods3 != null) {
            //                flashGoods3.setStartTime(10);
            //                flashGoods3.setEndTime(20);
            //            }

            flashTimerTask =
                    new FlashTimerTask(flashGoods1, flashGoods2, flashGoods3, mServerNowTime);
            flashTimerTask.startTimer();
        }
    }

    @Override
    public void loadNewGoodsList(
            final boolean isRefreshing, String tag, final OnLoadGoodsListener listener) {

        if (isRefreshing) {
            goodsListPager = 1;
        }

        PagerRequest request = new PagerRequest();
        request.setUrl(Urls.HOME_NEW_GOODS_LIST);
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setPage(goodsListPager);
        request.setPageSize(Common.PAGER_SIZE);

        mNetBiz.sendGetRequest(request, QueryGoodsListResponse.class, new NetListener<QueryGoodsListResponse>() {
            @Override
            public void onSuccess(QueryGoodsListResponse response) {

                goodsListPager++;

                List<Goods> goodsLines = response.getData().getGoods();

                if (isRefreshing) {
                    mGoodsGridList.clear();
                    mGoodsList.clear();
                }

                if (goodsLines != null) {
                    mGoodsList.addAll(goodsLines);
                    for (int i = 0; i < goodsLines.size(); i += 2) {
                        Goods goods1 = null;
                        Goods goods2 = null;
                        try {
                            goods1 = goodsLines.get(i);
                            goods2 = goodsLines.get(i + 1);
                        } catch (IndexOutOfBoundsException e) {
                        }
                        mGoodsGridList.add(new DoubleGoods(goods1, goods2));
                    }
                }
                if (listener != null) {
                    listener.onSuccess(mGoodsList, mGoodsGridList, goodsLines == null || goodsLines.size() == 0, response.hasMoreData());
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    @Override
    public void getFrame(String tag, final OnFrameListener listener) {
        BaseRequest request = new BaseRequest();
        request.setUrl(Urls.GET_FRAME);
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));

        mNetBiz.sendGetRequest(request, QueryFrameResponse.class, new NetListener<QueryFrameResponse>() {
            @Override
            public void onSuccess(QueryFrameResponse response) {
                QueryFrameResponse.Data data = response.getData();
                if (data == null) {
                    return;
                }

                QueryFrameResponse.Frame frame = data.getFrame();

                if (frame == null) {
                    return;
                }

                if (listener != null) {
                    listener.onSuccess(frame);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                return false;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                return false;
            }

            @Override
            public void onFinal() {
                if (listener != null) {
                    listener.onFinal();
                }
            }
        });
    }

    @Override
    public void getSecondKillData(String tag, final OnLoadSecondKillListener listener) {

        BaseRequest request = new BaseRequest();
        request.setUrl(Urls.GET_SECOND_KILL_GOODS);
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));

        mNetBiz.sendPostRequest(request, QuerySecondKillResponse.class, new NetListener<QuerySecondKillResponse>() {
            @Override
            public void onSuccess(QuerySecondKillResponse response) {
                // 最新的秒杀数据
                SecondKill newSecondKill = response.getSecondKill();

                try {
                    if (!(mHomeDisplayItems.get(secondKillIndex) instanceof HomeSecondKillListItem) || newSecondKill == null) {
                        return;
                    }
                } catch (IndexOutOfBoundsException e) {
                    return;
                }

                LogUtils.d("位置找对了，就是秒杀ListItem");

                List<Goods> secondKillGoodsList = newSecondKill.getGoodsList();

                if (secondKillGoodsList == null || secondKillGoodsList.size() == 0) {
                    // 如果没有新的秒杀数据
                    // 直接移除掉秒杀Item
                    mHomeDisplayItems.remove(secondKillIndex);

                    LogUtils.d("没有最新的秒杀信息，移除 秒杀ListItem");
                } else {

                    LogUtils.d("替换为最新的秒杀活动信息");

                    // 有数据则替换
                    HomeSecondKillListItem secondKillListItem = (HomeSecondKillListItem) mHomeDisplayItems.get(secondKillIndex);

                    //                    // 将serverNowTime 保存到新的对象中
                    //                    SecondKill oldSecondKill = secondKillListItem
                    // .getContentData();
                    //                    long serverNowTime = oldSecondKill
                    // .getServerNowTime();
                    //
                    //                    newSecondKill.setServerNowTime(serverNowTime);

                    // 重新开始倒计时
                    // 如果有下一场活动才倒计时
                    doSecondKillTimer(newSecondKill);
                    // 给 HomeSecondKillListItem 重新绑定数据
                    secondKillListItem.setContentData(newSecondKill);
                }

                // 刷新UI
                if (listener != null) {
                    listener.onSuccess();
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                return false;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                return false;
            }

            @Override
            public void onFinal() {
                if (listener != null) {
                    listener.onFinal();
                }
            }
        });
    }
}
